package Controller;


import Model.JZFWTJ;
import Service.JZFWTJService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@RequestMapping("/JZFWTJ")
@Controller
public class JZFWTJController {

    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Resource
    JZFWTJService jzfwtjService;


    /**
     * 获得可控范围表列表
     */
    @RequestMapping(value = "/getAllList",produces ={"application/json;charset=UTF-8"})
    @ResponseBody
    public PageInfo getAllLogList(@RequestParam(value = "page",defaultValue = "1")Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit){
        PageHelper.startPage(page, limit);
        List<JZFWTJ> jzfwtjs = jzfwtjService.getAllList();
        PageInfo pdr = new PageInfo(jzfwtjs);
        return pdr;
    }

    /**
     * 通过片区查询可控范围表
     */
    @RequestMapping(value = "/findBySection",produces ={"application/json;charset=UTF-8"} )
    @ResponseBody
    public List<JZFWTJ> findBySection(@RequestParam("kkfw_section")String kkfw_section){
        System.out.println(kkfw_section);
        List<JZFWTJ> jzfwtjs =null;
        try {

            jzfwtjs = jzfwtjService.findBySection(kkfw_section);
            System.out.println("角色列表查询" + jzfwtjs);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("角色查询异常！", e);
        }
        System.out.println("角色列表：" + jzfwtjs);
        return jzfwtjs;
    }


    /**
     * 删除可控范围表
     */
    @RequestMapping(value = "/delKkfwb", method = RequestMethod.POST)
    @ResponseBody
    public String delKkfwb(@RequestParam("id") int id) {
        logger.debug("删除可控范围表及序号" + id);
        try {
            if (id > 0) {
                return jzfwtjService.delKkfwb(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除可控范围表异常！", e);
        }
        return "删除可控范围表出错";
    }



    /**
     * 更新可控范围表
     */
    @RequestMapping(value = "/updateKkfwb", method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    @ResponseBody
    public String updateKkfwb(JZFWTJ jzfwtj, HttpSession session) {
        try {
            System.out.println("开始更新");
            String abc=jzfwtjService.updateKkfwb(jzfwtj, session);
            return "{\"msg\":\"ok\"}";
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新异常！", e);
            return "操作异常，请您稍后再试";
        }
    }



    /**
     * 上传可控范围表
     */
    @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        System.out.println("进入controller" );
        String flag = "02";// 上传标志
        if (!file.isEmpty()) {
            try {
                String originalFilename = file.getOriginalFilename();// 原文件名字
                System.out.println("文件名：" + originalFilename);
                InputStream is = file.getInputStream();// 获取输入流
                flag = jzfwtjService.uploadFile(is, originalFilename);
                System.out.println("controller flag：" + flag);
                return "{\"msg\":\"ok\"}";
            } catch (Exception e) {
                flag = "03";// 上传出错
                e.printStackTrace();
                System.out.println("controller flag：" + flag);
            }
        }
        System.out.println("controller 返回flag：" + flag);
        return "{\"msg\":\"error\"}";
    }


    /**
     *导出可控范围表
     */

    @RequestMapping(value = "/outputFile", produces = "application/form-data; charset=utf-8")
    @ResponseBody
    public void OutputExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");

        List<JZFWTJ> list = jzfwtjService.getAllList();
        System.out.println(list);
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet页
        HSSFSheet sheet = wb.createSheet("可控范围表");
        //创建标题行
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("kkfw_ID");
        titleRow.createCell(1).setCellValue("kkfw_section");
        titleRow.createCell(2).setCellValue("kkfw_area");
        titleRow.createCell(3).setCellValue("kkfw_apartment");

        //遍历将数据放到excel列中
        for (JZFWTJ user : list) {
            //创建标题列
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(user.getKkfw_ID());
            dataRow.createCell(1).setCellValue(user.getKkfw_section());
            dataRow.createCell(2).setCellValue(user.getKkfw_area());
            dataRow.createCell(3).setCellValue(user.getKkfw_apartment());
        }

        // 设置下载时客户端Excel的名称   （上面注释的改进版本，上面的中文不支持）
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String("可控范围表".getBytes(), "iso-8859-1") + ".xls");


        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }



    /**
     * 得到街镇服务统计列表并机构查询
     */

    @RequestMapping(value = "/getFwjgList",produces ={"application/json;charset=UTF-8"})
    @ResponseBody
    public PageInfo getFwjgList(@RequestParam(value = "page",defaultValue = "1")Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit,@RequestParam(value="department_name" ,required = false)String department_name) {
        PageHelper.startPage(page, limit);
        List<Map<String,Object>> maps = jzfwtjService.getFwjgList(department_name);
        PageInfo pdr = new PageInfo(maps);
        return pdr;

    }



}
